package org.dromara.web.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.enums.DeviceStatus;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.web.core.BaseController;
import org.dromara.iot.domain.bo.IotElevatorBo;
import org.dromara.iot.domain.bo.IotElevatorEventBo;
import org.dromara.iot.domain.vo.IotElevatorEventVo;
import org.dromara.iot.domain.vo.IotElevatorVo;
import org.dromara.iot.enums.DeviceElevatorEventTypeEnum;
import org.dromara.iot.service.IIotElevatorEventService;
import org.dromara.iot.service.IIotElevatorService;
import org.dromara.system.domain.bo.SysCommunityBo;
import org.dromara.system.domain.vo.SysCommunityVo;
import org.dromara.system.service.ISysCommunityService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 大屏接口
 */
@SaIgnore
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/index/screen")
public class WebBigScreenController extends BaseController {
    private final IIotElevatorService iotElevatorService;
    private final IIotElevatorEventService iotElevatorEventService;
    private final ISysCommunityService sysCommunityService;
    @Value("${alarm.days:-7}")
    private Integer alarmDays;

    /**
     * 报警次数
     */
    @GetMapping(value = "alarmCount")
    public R<JSONObject> alarmCount() {
        IotElevatorEventBo bo = new IotElevatorEventBo();
        DateTime endTime = DateUtil.endOfDay(new Date());
        bo.setStartTime(DateUtil.offsetDay(endTime, alarmDays));
        bo.setEndTime(endTime);
        TableDataInfo<IotElevatorEventVo> iotElevatorEventVos = iotElevatorEventService.queryWarningList(bo, new PageQuery());
        Map<String, Long> collect = iotElevatorEventVos.getRows().stream().collect(
                Collectors.groupingBy(i -> DateUtil.formatDate(i.getReportTime()), Collectors.counting())
        );
        JSONObject json = JSONUtil.createObj();
        json.set("dateList", collect.keySet());
        json.set("numList", collect.values());
        return R.ok(json);
    }

    /**
     * 报警排名
     */
    @GetMapping(value = "alarmRank")
    public R<JSONArray> alarmRank() {
        IotElevatorEventBo bo = new IotElevatorEventBo();
        DateTime endTime = DateUtil.endOfDay(new Date());
        bo.setStartTime(DateUtil.offsetDay(endTime, alarmDays));
        bo.setEndTime(endTime);
        TableDataInfo<IotElevatorEventVo> iotElevatorEventVos = iotElevatorEventService.queryWarningList(bo, new PageQuery());
        Map<String, Long> collect = iotElevatorEventVos.getRows().stream().collect(
                Collectors.groupingBy(IotElevatorEventVo::getElevatorName, Collectors.counting())
        );
        JSONArray array = JSONUtil.createArray();
        collect.entrySet().stream().sorted((a, b) -> Math.toIntExact(b.getValue() - a.getValue())).limit(8).forEach(entry -> {
            JSONObject jsonObject = JSONUtil.createObj();
            jsonObject.set("name", entry.getKey());
            jsonObject.set("value", entry.getValue());
            array.add(jsonObject);
        });
        return R.ok(array);
    }

    /**
     * 设备总览
     */
    @GetMapping(value = "deviceOverview")
    public R<JSONObject> deviceOverview() {
        IotElevatorEventBo bo = new IotElevatorEventBo();
        DateTime endTime = DateUtil.endOfDay(new Date());
        bo.setStartTime(DateUtil.offsetDay(endTime, alarmDays));
        bo.setEndTime(endTime);
        JSONObject json = JSONUtil.createObj();
        List<IotElevatorVo> iotElevatorVos = iotElevatorService.queryList(new IotElevatorBo());
        Long alarmNum = iotElevatorEventService.queryWarningCount(bo);
        json.set("totalNum", iotElevatorVos.size());
        json.set("onlineNum", iotElevatorVos.stream().filter(elevator -> DeviceStatus.ONLINE.getStatus().equals(elevator.getStatus())).count());
        json.set("offlineNum", iotElevatorVos.stream().filter(elevator -> DeviceStatus.OFFLINE.getStatus().equals(elevator.getStatus())).count());
        json.set("alarmNum", alarmNum);
        return R.ok(json);
    }

    /**
     * 设备提醒
     */
    @GetMapping(value = "deviceRemind")
    public R<List<IotElevatorEventVo>> deviceRemind(PageQuery pageQuery) {
        IotElevatorEventBo bo = new IotElevatorEventBo();
        bo.setEventType(DeviceElevatorEventTypeEnum.OFFLINE_ONLINE_EVENT.getCode());
        TableDataInfo<IotElevatorEventVo> iotElevatorEventVoTableDataInfo = iotElevatorEventService.queryPageList(bo, pageQuery);
        return R.ok(iotElevatorEventVoTableDataInfo.getRows());
    }

    /**
     * 安装计划
     */
    @GetMapping(value = "installPlan")
    public R<JSONObject> installPlan() {
        JSONObject json = JSONUtil.parseObj("{\"category\":[\"徐州市\",\"铁岭市\",\"衡水市\",\"天津市\",\"九江市\",\"石嘴山市\",\"南平市\",\"六盘水市\",\"三沙市\",\"赤峰市\",\"海西蒙古族藏族自治州\",\"呼伦贝尔市\",\"香港岛\",\"海南藏族自治州\",\"汉中市\",\"连江县\",\"锡林郭勒盟\",\"南平市\",\"泉州市\",\"德阳市\",\"七台河市\",\"淮北市\",\"离岛\",\"天津市\",\"黄冈市\",\"牡丹江市\",\"北京市\",\"台州市\",\"龙岩市\",\"佳木斯市\"],\"barData\":[59,68,73,56,28,22,85,73,39,76,26,37,31,35,16,17,23,64,57,95,70,98,44,29,14,16,31,44,27,49],\"lineData\":[62,114,130,83,53,88,148,122,43,153,31,98,102,70,36,39,108,163,135,101,129,125,82,41,62,79,39,86,73,97],\"rateData\":[\"95\",\"60\",\"56\",\"67\",\"53\",\"25\",\"57\",\"60\",\"91\",\"50\",\"84\",\"38\",\"30\",\"50\",\"44\",\"44\",\"21\",\"39\",\"42\",\"94\",\"54\",\"78\",\"54\",\"71\",\"23\",\"20\",\"79\",\"51\",\"37\",\"51\"]}");
        return R.ok(json);
    }

    /**
     * 小区分布
     */
    @GetMapping(value = "communityDistribution")
    public R<JSONObject> communityDistribution(String regionCode) {
//        @TODO 没有市划分
        List<SysCommunityVo> sysCommunityVos = sysCommunityService.queryList(new SysCommunityBo());
        Map<String, Long> collect = sysCommunityVos.stream().collect(
                Collectors.groupingBy(c -> c.getAddress().split("/")[0], Collectors.counting())
        );
        JSONArray array = JSONUtil.createArray();
        collect.entrySet().stream().sorted((a, b) -> Math.toIntExact(b.getValue() - a.getValue())).forEach(entry -> {
            JSONObject jsonObject = JSONUtil.createObj();
            jsonObject.set("name", entry.getKey());
            jsonObject.set("value", entry.getValue());
            array.add(jsonObject);
        });
        JSONObject obj = JSONUtil.createObj();
        obj.set("dataList", array);
        obj.set("regionCode", regionCode);
        return R.ok(obj);
    }

    /**
     * 实时预警
     */
    @GetMapping(value = "realTimeWarning")
    public R<List<IotElevatorEventVo>> realTimeWarning(PageQuery pageQuery) {
        TableDataInfo<IotElevatorEventVo> iotElevatorEventVos = iotElevatorEventService.queryWarningList(new IotElevatorEventBo(), pageQuery);
        return R.ok(iotElevatorEventVos.getRows());
    }

    /**
     * 设备分布@TODO
     */
    @GetMapping(value = "deviceDistribution")
    public R<JSONObject> deviceDistribution() {
        JSONObject objects = JSONUtil.parseObj("{\"dataList\":[{\"name\":\"四川省\",\"value\":233},{\"name\":\"海南省\",\"value\":940},{\"name\":\"澳门特别行政区\",\"value\":86},{\"name\":\"陕西省\",\"value\":601},{\"name\":\"上海\",\"value\":994},{\"name\":\"江苏省\",\"value\":777},{\"name\":\"安徽省\",\"value\":626},{\"name\":\"辽宁省\",\"value\":983}],\"regionCode\":\"china\"}");
        return R.ok(objects);
    }
}
